package day39_other;

/**
 * @ClassName Solution
 * @Description TODO
 * @Author clockTown
 * @Date 2021/6/17 20:11
 * @Version 1.0
 */
public class Solution {
    public int solve(int[] nums, int x) {
        if (x == 0 || nums == null || nums.length == 0){
            return 0;
        }
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        int target = sum - x;
        if (target < 0) {
            return -1;
        }

        int res = Integer.MIN_VALUE;
        int left = 0, right = 0;

        while (right < nums.length){
            target -= nums[right++];
            while (target < 0){
                target += nums[left++];
            }
            if (target == 0) {
                res = Math.max(res, right - left);
            }
        }

        return res == Integer.MIN_VALUE ? -1: nums.length - res;
    }
}
